package com.hitqz.robot.dispatch.netty.dispatch;

import cn.hutool.extra.spring.SpringUtil;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.business.entity.RobotGroupEntity;
import com.hitqz.robot.biz.service.RobotGroupService;
import com.hitqz.robot.daemon.quartz.constants.RobotQuartzEnum;
import com.hitqz.robot.dispatch.netty.service.DispatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2024/8/16
 */
@Slf4j
//@RequiredArgsConstructor
@Component
public class RobotDispatch {

    public static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,20,
            1L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(20),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.DiscardPolicy());

    /**
     *
     * @return
     */
    public String dispatch() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("dispatch");
        // 获取机器人组服务
        RobotGroupService robotGroupService = SpringUtil.getBean(RobotGroupService.class);
        // 获取缓存
        Cache<Integer, List<RobotEntity>> robotDispatch = SpringUtil.getBean("robotDispatch");
        // 获取调度服务
        DispatchService dispatchService = SpringUtil.getBean(DispatchService.class);

        // 循环处理每个机器人组
        for (Integer key : robotDispatch.asMap().keySet()) {
            // 根据键获取机器人实体列表
            List<RobotEntity> robotEntityList = robotDispatch.getIfPresent(key);
            if (robotEntityList.size() <=1) {
                continue;
            }
            try {
                // 获取机器人组实体
                RobotGroupEntity robotGroupEntity = robotGroupService.getById(robotEntityList.get(0).getGroupId());
                // 执行调度算法
                threadPool.execute(() -> {
                    dispatchService.calAlgorithm(robotGroupEntity.getDispatchAlgorithm(), robotGroupEntity.getId(), robotEntityList);
                });
            } catch (Exception e) {
                // 记录异常
                log.error("Error during dispatch: " + e.getMessage(), e);
            }
        }
        stopWatch.stop();
        //log.info("调度一次计算:" + stopWatch.prettyPrint());
        // 返回成功状态码
        return RobotQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }


}
